package com.itheima.springboottlias.aspect;

import com.itheima.springboottlias.common.utils.JwtUtils;
import com.itheima.springboottlias.mapper.OperateLogMapper;
import com.itheima.springboottlias.pojo.OperateLog;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;


/**
 * @author iTaotao
 * @date 2023/7/19 16:10
 * @desciption: 记录系统操作日志
 */
@Aspect
@Slf4j
@Component
public class OperatorLog implements HandlerInterceptor {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Pointcut("@annotation(com.itheima.springboottlias.annotation.SysLog)")
    public void pt() {
    }


    @Around("pt()")
    public Object record(ProceedingJoinPoint joinPoint) throws Throwable {
//        1.操作人
        String token = request.getHeader("token");
        log.info("请求头中的令牌:{}", token);
        Claims claims = JwtUtils.parseJWT(token);
        Integer operateUser = (Integer) claims.get("userId", Integer.class);

//        2.操作时间
        LocalDateTime operateTime = LocalDateTime.now();

//        3.操作的目标类名
        String name = joinPoint.getTarget().getClass().getName();
        log.info("操作的目标类名: {}", name);


//        4.操作的方法名
        String methodName = joinPoint.getSignature().getName();
        log.info("操作的方法名: {}", methodName);
//        5.方法参数
        Object[] args = joinPoint.getArgs();
        log.info("方法参数:{}", Arrays.toString(args));
        String json = com.alibaba.fastjson.JSONObject.toJSONString(args);
//        6.返回值
        long start = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        String result = com.alibaba.fastjson.JSONObject.toJSONString(args);
        long end = System.currentTimeMillis();
        log.info("返回值: {}", proceed);
//        7.方法执行耗时 ms
        log.info("执行时间: {} ms", end - start);
        Long costTime = end - start;
        OperateLog operateLog = new OperateLog();
        operateLog.setId(null);
        operateLog.setOperateUser(operateUser);
        operateLog.setOperateTime(operateTime);
        operateLog.setClassName(name);
        operateLog.setMethodName(methodName);
        operateLog.setMethodParams(json);
        operateLog.setReturnValue(result);
        operateLog.setCostTime(costTime);
        operateLogMapper.insert(operateLog);
        return proceed;


    }
}
